<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button v-if="isAuth('goods:class:add')" type="primary" @click="updateHandle(null)">新增</el-button>
        <el-button v-if="isAuth('goods:class:remove')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="classId"
        header-align="center"
        align="center"
        label="ID">
      </el-table-column>
      <el-table-column
        prop="className"
        header-align="center"
        align="center"
        label="分类名">
        <template slot-scope="scope">
          {{scope.row.className}}
            <el-button type="primary" size="mini" style="float: right;" plain @click="parentClassId = scope.row.classId
            openSubClassHandle(scope.row.classId)">查看下级分类</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="typeName"
        header-align="center"
        align="center"
        label="类型">
      </el-table-column>
      <el-table-column
        prop="display"
        header-align="center"
        align="center"
        label="显示">
        <template slot-scope="scope">
          {{scope.row.display === 1 ? '是' : '否'}}
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" v-if="isAuth('goods:class:modify')"  @click="updateHandle(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="clickAddSubordinate(scope.row.classId)">添加下级</el-button>
          <el-button type="text" size="small" v-if="isAuth('goods:class:remove')"  @click="deleteHandle(scope.row.classId)">删除</el-button>
          <el-button type="text" size="small" @click="specsHandle(scope.row.goodsTypeId)">规格信息</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-dialog
      title="查看"
      :visible.sync="subClassListVisible"
      style="height: 700px"
      width="30%">
      <el-table
        :data="subClassList"
        border
        style="width: 100%">
        <el-table-column
          prop="classId"
          label="ID">
        </el-table-column>
        <el-table-column
          prop="iconUrl"
          label="图标">
          <template slot-scope="scope">
            <el-popover
              style="margin-left: 5px;margin-bottom: 5px"
              placement="right"
              title=""
              trigger="hover">
              <img v-if="scope.row.iconUrl !== null" :src="'https://image.yilianbaihui.cn/' + scope.row.iconUrl" style="max-width: 300px"/>
              <img slot="reference" v-if="scope.row.iconUrl !== null" :src="'https://image.yilianbaihui.cn/' + scope.row.iconUrl" :alt="'https://image.yilianbaihui.cn/' + scope.row.iconUrl" style="max-height: 30px;max-width: 80px"/>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="className"
          label="分类名">
        </el-table-column>
        <el-table-column
          prop="display"
          header-align="center"
          align="center"
          label="显示">
          <template slot-scope="scope">
            {{scope.row.display === 1 ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" v-if="isAuth('goods:class:modify')"  @click="updateHandle(scope.row)">修改</el-button>
            <el-button type="text" size="small" v-if="isAuth('goods:class:remove')"  @click="deleteHandle(scope.row.classId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <el-dialog
      :title="updateData.id === 0 ? '新增':'修改'"
      :visible.sync="updateVisible"
      style="height: 700px"
      width="30%">
      <el-form ref="updateData" :model="updateData" label-width="80px">
        <el-form-item label="分类名称" placeholder="请输入">
          <el-input v-model="updateData.className"></el-input>
        </el-form-item>
        <!-- <el-form-item label="类型" v-if="updateData.goodsTypeId === 20">
          <el-select v-model="updateData.goodsTypeId" placeholder="请选择" value="">
            <el-option v-for="item in goodsType" :key="item.id"  :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否显示">
          <el-select v-model="updateData.display" placeholder="请选择" value="">
            <el-option :key="1" label="显示" :value="1"></el-option>
            <el-option :key="0" label="不显示" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload
            class="avatar-uploader"
            :action="this.$http.adornUrl(`/goods/class/uploadGoodsClassSpecImg?token=${this.$cookie.get('token')}`)"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="updateData.iconUrl != null && updateData.iconUrl !== ''" :src="'https://image.yilianbaihui.cn/' + updateData.iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示顺序" v-if="updateData.isDisplay">
          <el-input v-model="updateData.sequence"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateHandle">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="查看"
      :visible.sync="specsListVisible"
      style="height: 700px"
      width="30%">
      <el-table
        :data="specsList"
        border
        style="width: 100%">
        <el-table-column
          prop="name"
          align="center"
          label="规格名">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" v-if="isAuth('goods:class:remove')"  @click="deleteHandle(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="querySpecsList">添加</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加规格"
      :visible.sync="addSpecsVisible"
      style="height: 700px"
      width="30%">
      <el-table
        :data="addSpecsList"
        border
        style="width: 100%">
        <el-table-column
          prop="name"
          align="center"
          label="规格名">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addSpecsHandle(scope.row.id)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      :title="this.dataForm.classId !== 0 ? '新增下级':'修改'"
      :visible.sync="addSubordinateVisible"
      style="height: 700px"
      width="30%">
      <el-form :model="this.addSubordinate" label-width="80px">
        <el-form-item label="分类名称" placeholder="请输入">
          <el-input v-model="addSubordinate.className"></el-input>
        </el-form-item>
        <!-- <el-form-item label="类型" v-if="updateData.goodsTypeId === 20">
          <el-select v-model="updateData.goodsTypeId" placeholder="请选择" value="">
            <el-option v-for="item in goodsType" :key="item.id"  :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否显示">
          <el-select v-model="addSubordinate.display" placeholder="请选择" value="">
            <el-option :key="1" label="显示" :value="1"></el-option>
            <el-option :key="0" label="不显示" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload
            class="avatar-uploader"
            :action="this.$http.adornUrl(`/goods/class/uploadGoodsClassSpecImg?token=${this.$cookie.get('token')}`)"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload">
            <img v-if="addSubordinate.iconUrl != null && addSubordinate.iconUrl !== ''" :src="'https://image.yilianbaihui.cn/' + addSubordinate.iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input type="number" v-model="addSubordinate.sequence"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addSubordinateVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubordinateHandle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <add-goods-class v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update> -->
  </div>
</template>

<script>
  export default {
    data () {
      return {
        dataForm: {
          keywords: '',
          classId: 0
        },
        parentClassId: 0,
        addSubordinate: {
          className: '',
          display: '',
          iconUrl: '',
          sequence: ''
        },
        updateData: {},
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        addSubordinateVisible: false,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        subClassList: [],
        subClassListVisible: false,
        updateVisible: false,
        specsListVisible: false,
        specsList: [],
        goodsType: [],
        goodsTypeId: 0,
        addSpecsList: [],
        addSpecsVisible: false
      }
    },
    activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/goods/class/queryGoodsClassList'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'keywords': this.dataForm.keywords
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.data.list
            this.totalPage = data.data.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      clickAddSubordinate (classId) {
        debugger
        this.dataForm.classId = classId
        this.addSubordinateVisible = true
        this.addSubordinate.className = ''
        this.addSubordinate.display = ''
        this.addSubordinate.iconUrl = ''
        this.addSubordinate.sequence = ''
      },
      updateHandle (data) {
        debugger
        if (data === null) {
          this.$http({
            url: this.$http.adornUrl('/goods/class/queryGoodsTypeList'),
            method: 'post'
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.goodsType = data.data
            } else {
              this.$message.error(data.msg)
            }
          })
          this.updateData = {
            id: 0,
            className: '',
            goodsTypeId: 20,
            display: 1,
            sequence: 0,
            isDisplay: true,
            iconUrl: ''
          }
        } else {
          this.updateData = data
          if (this.updateData.classId === undefined) {
            this.updateData.isDisplay = false
          } else {
            this.updateData.isDisplay = true
          }
        }
        this.updateVisible = true
      },
      // 新增 / 修改
      addOrUpdateHandle () {
        let than = this
        this.$http({
          url: this.$http.adornUrl(`/goods/class/${this.updateData.id === 0 ? `add` : `modifyById`}`),
          method: 'post',
          data: this.$http.adornData({
            'id': this.updateData.classId || 0,
            'className': this.updateData.className,
            'sequence': this.updateData.sequence || 0,
            'display': this.updateData.display || 0,
            'goodsTypeId': this.updateData.goodsTypeId,
            'iconUrl': this.updateData.iconUrl
          }, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            if (than.updateData.id === 0) {
              than.openSubClassHandle(than.parentClassId)
            }
            than.updateVisible = false
            than.$message.success(this.updateData.id === 0 ? '添加成功' : '修改成功')
          } else {
            than.$message.error('修改失败')
          }
          than.parentClassId = ''
        })
        this.updateVisible = false
        this.getDataList()
      },
      specsHandle (id) {
        this.goodsTypeId = id
        this.$http({
          url: this.$http.adornUrl('/goods/class/querySpecsListByTypeId'),
          method: 'post',
          data: this.$http.adornData(id, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.specsList = data.data || []
            this.specsListVisible = true
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      addSubordinateHandle () {
        this.$http({
          url: this.$http.adornUrl(`/goods/class/addSecondLevelClass`),
          method: 'post',
          data: this.$http.adornData({
            'id': null,
            'className': this.addSubordinate.className,
            'sequence': this.addSubordinate.sequence || 0,
            'display': this.addSubordinate.display || 0,
            'iconUrl': this.addSubordinate.iconUrl,
            'parentId': this.dataForm.classId
          }, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('添加成功')
          //   if (than.updateData.id === 0) {
          //     than.openSubClassHandle(than.parentClassId)
          //   }
          //   than.updateVisible = false
          //   than.$message.success(this.updateData.id === 0 ? '添加成功' : '修改成功')
          // } else {
          //   than.$message.error('修改失败')
          // }
          // than.parentClassId = ''
            this.addSubordinateVisible = false
          }
        })
        this.getDataList()
      },
      // 删除
      deleteHandle (id) {
        let ids = id ? [id] : this.dataListSelections.map(item => {
          return item.classId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data
          if (this.specsListVisible) {
            data = ids[0]
          } else {
            data = ids
          }
          this.$http({
            url: this.$http.adornUrl(`/goods/class/${this.specsListVisible ? 'specsRemove/' + this.goodsTypeId : 'remove'}`),
            method: 'post',
            data: this.$http.adornData(data, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              if (!this.subClassListVisible) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    this.getDataList()
                  }
                })
              }

              if (this.specsListVisible) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    this.specsHandle(this.goodsTypeId)
                  }
                })
              } else {
                this.openSubClassHandle(this.parentClassId)
                this.parentClassId = ''
              }
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      openSubClassHandle (id) {
        this.$http({
          url: this.$http.adornUrl(`/goods/class/queryGoodsSubClassById/${id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.subClassList = data.data
            this.subClassListVisible = true
          }
        })
      },
      // 添加规格
      querySpecsList () {
        this.$http({
          url: this.$http.adornUrl(`/goods/class/querySpecsList`),
          method: 'post',
          data: this.$http.adornData(this.specsList.map(list => { return list.id }) || [], false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.addSpecsList = data.data
            this.addSpecsVisible = true
          }
        })
      },
      // 添加规格
      addSpecsHandle (id) {
        this.$confirm(`确定把该规格添加到当前分类吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/goods/class/addClassSpecs/${this.goodsTypeId}`),
            method: 'post',
            data: this.$http.adornData(id, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.specsHandle(this.goodsTypeId)
                  this.specsList.push({id: id})
                  this.querySpecsList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      handleAvatarSuccess (res, file) {
        this.updateData.iconUrl = res.data
      },
      handleAvatarSuccess2 (res, file) {
        this.addSubordinate.iconUrl = res.data
      },
      beforeAvatarUpload (file) {
        let suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (suffix !== 'jpg' && suffix !== 'png' && suffix !== 'gif') {
          this.$message.error('上传文件只能是 jpg、png、gif格式!')
          return false
        }

        if (file.size > 1024 * 1024) {
          this.$message.error('上传图片大小不能超过1M！')
          return false
        }
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
